package com.facishare.open.mongo.dao.impl;

import com.facishare.open.mongo.dao.UserDao;
import com.facishare.open.mongo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by linchf on 2016/8/23.
 */
@Repository
public class UserDaoImpl implements UserDao{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<User> findList(int skip, int limit) {
        Query query = new Query();
        query.with(new Sort(new Sort.Order(Sort.Direction.ASC, "_id")));
        query.skip(skip).limit(limit);
        return this.mongoTemplate.find(query, User.class);
    }

    @Override
    public List<User> findListByUsername(String username) {
        Query query = new Query();
        Pattern pattern = Pattern.compile("^8.*$", Pattern.CASE_INSENSITIVE);
        query.addCriteria(new Criteria("username").regex(pattern));

        return this.mongoTemplate.find(query, User.class);
    }

    @Override
    public User findOne(String id) {
        Query query = new Query();
        query.addCriteria(new Criteria("_id").is(id));
        return this.mongoTemplate.findOne(query, User.class);
    }

    @Override
    public User findOneByUsername(String username) {
        Query query = new Query();
        query.addCriteria(new Criteria("username").is(username));
        return this.mongoTemplate.findOne(query, User.class);
    }

    @Override
    public void insert(User entity) {
        this.mongoTemplate.insert(entity);
    }

    @Override
    public void update(User entity) {
        Query query = new Query();
        query.addCriteria(new Criteria("_id").is(entity.getId()));
        Update update = new Update();
        update.set("username", entity.getUsername());
        update.set("password", entity.getPassword());
        this.mongoTemplate.updateFirst(query, update, User.class);
    }

    @Override
    public void delete(User entity) {
        Query query = new Query();
        if (entity.getUsername() != null) {
            query.addCriteria(new Criteria("username").is(entity.getUsername()));
        }
        if (entity.getPassword() != null) {
            query.addCriteria(new Criteria("password").is(entity.getPassword()));
        }
        this.mongoTemplate.remove(query, User.class);
    }


}
